<?php
namespace App\CrontabTask;

use App\Common as com;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;

class Base {

	protected string $taskName;

	/**
	 * @Inject()
	 * @var StdoutLoggerInterface
	 */
	protected StdoutLoggerInterface $logger;

	/**
	 * 执行（加锁）
	 * @param \Closure $callback 执行回调
	 * @param int $lockExpire 锁超时
	 * @return mixed 返回 $callback 执行结果。
	 * @throws
	 */
	protected function runOfLock( \Closure $callback, int $lockExpire ):mixed {
		$this->logger->info( date('Y-m-d H:i:s', time() ) . '[定时任务]' . $this->taskName . '...启动' );
		//
		$lock = com\Lib\Lock::new( static::class );
		if( ! $lock->lock( $lockExpire ) ){
			$this->logger->error( date('Y-m-d H:i:s', time() ) . '[定时任务]' . $this->taskName . '，终止执行，原因上锁失败...结束' );
			throw com\Lib\Err\Exception::makeOfNew( '', com\Lib\Err\Code::$sysLockLose );
		}
		//
		try {
			$res = $callback();
			$lock->unlock();
			$this->logger->info( date('Y-m-d H:i:s', time() ) . '[定时任务]' . $this->taskName . '...完成' );
			//
			return $res;
		}catch( \Exception $e ){
			$this->logger->error(date('Y-m-d H:i:s', time()) . '[定时任务]' . $this->taskName . '，发生异常。异常信息如下' );
			com\Lib\Err\Exception::showSimpleShowExceptionInfo( $e );
			$lock->unlock();
			throw $e;
		}
	}
	
}